from django.shortcuts import render
from rest_framework import status
from rest_framework.viewsets import ViewSet

from dingxiang.utils.alipaysdk import Alipay
from rest_framework.response import Response

from rest_framework.decorators import action

from orders.models import OrderModel
from coupon.models import CouponManage
from doctors.serial import DoctorDetailSerializer
# Create your views here.

class AlipayAPI(ViewSet):
    @action(methods=['GET'], detail=False)
    def link(self,request):
        order_id = request.query_params.get('order_id')
        try:
            order = OrderModel.objects.get(id=order_id)
            if order.order_status > 0:
                return Response({'message':'订单不能重复支付或订单已经超时'},status=status.HTTP_204_NO_CONTENT)

        except OrderModel.DoesNotExist:
            print('订单不存在，请检查传入的参数是否正确')
            return Response({'message': '订单不存在,请重新下单！'}, status=status.HTTP_204_NO_CONTENT)

        alipay = Alipay()
        link = alipay.page_pay(order.order_number,order.real_price,order.name)
        print('----------------------查看支付宝返回的结果---------------------------')
        print(link)
        print('--------------------------支付宝返回结果--------------------------------------------')
        return Response(link)

    @action(methods=['GET'],detail=False)
    def return_result(self,request):
        # 所有查询参数，转化成字典格式数据
        data = request.query_params.dict()
        print('5555555555555555555555555555555555555555555555555555555555打印支付宝同步通知结果...',data)
        # 校验数据，验签
        alip = Alipay()
        success = alip.check_sign(data)
        if not success:
            return Response({'message':'支付宝同步通知结果不存在或者异常'},status=status.HTTP_204_NO_CONTENT)
        # 从支付宝同步通知结果中获取订单号
        order_number = data.get('out_trade_no')
        # 根据订单号查询订单信息
        try:
            order = OrderModel.objects.get(order_number=order_number)
            if order.order_status > 1:
                return Response({'message':'订单超时或已取消...'},status=status.HTTP_204_NO_CONTENT)
        except OrderModel.DoesNotExist:
            return Response({'message':'订单不存在...'},status=status.HTTP_204_NO_CONTENT)


        order_doctor = order.order_detail.all()

        doctor_list = [item.doctor for item in order_doctor]

        # 修改订单状态
        # 将当前支付成功的信息，和订单查询返回给前端
        # 修改状态：订单状态   优惠券状态：使用时间
        # 判断当前订单状态是否为0
        if order.order_status == 0:
            # 根据订单号查询订单信息
            # 后端异步通知无法接收   查询替代异步通知
            result = alip.query(order_number)
            # 支付结果以后端为准
            print('打印订单查询返回结果...')
            print(result)
            print('---------')
            # 判断支付结果是否成功
            if result.get('trade_status',None) in ['TRADE_SUCCESS','TRADE_FINISHED']:
                # 表示用后支付成功，修改订单状态
                order.pay_time = result.get('send_pay_date')
                order.order_status = 1
                order.save()
                # 如果订单有优惠券，则需要修改优惠券状态
                coupons_log = CouponManage.objects.filter(order=order).first()
                if coupons_log:
                    coupons_log.coupon_status = 1
                    coupons_log.use_time = order.pay_time
                    coupons_log.save()

            doctor_ser = DoctorDetailSerializer(instance=doctor_list,many=True)
            return Response({
                'pay_time':order.pay_time,
                'real_price':order.real_price,
                'doctor_list':doctor_ser.data


            })










